package com.yixinsoft.basic.web.aop;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.util.StringUtils;

/**
 * Created by hqy on 2016/06/11
 */
public class BaseCacheAspect implements InitializingBean {

	@Autowired
	private CacheManager cacheManager;
	
	private Cache cache;
	
	private String cacheName;
	
	public void setCacheName(String cacheName) {
		this.cacheName = cacheName;
	}
	
	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		cache = cacheManager.getCache(cacheName);
	}
	
	public void clear() {
		this.cache.clear();
	}
	
	public void evict(String key) {
		this.cache.evict(key);
	}
	
	public <T> T get(Object key) {
		if (StringUtils.isEmpty(key)) {
			return null;
		}
		Cache.ValueWrapper value = cache.get(key);
		if (value == null) {
			return null;
		}
		return (T)value.get();
	}
	
	public void put(String key, Object value) {
		this.cache.put(key, value);
	}
}
